<template>
  <div v-loading="interLoad" class="padding_10">
    <!-- 关联商品 -->
    <div>
      <el-button @click="$emit('send', {})">返回</el-button>
      <div
        class="background_gray padding_15"
        style="border-radius: 5px; font-weight: 600; margin-top: 15px"
      >
        商品类型
      </div>
      <!-- 商品关联类型 -->
      <div>
        <div
          v-for="(item, index) of relatedProducts"
          :key="index"
          class="goods_type_items"
          :class="{ select_style: index == counter }"
          @click="chooseAssoc(item, index)"
        >
          <div style="font-weight: 600">{{ item.type_name }}</div>
        </div>
      </div>
    </div>
    <!-- 商品基本信息 -->
    <div>
      <div
        class="background_gray padding_15"
        style="border-radius: 5px; font-weight: 600"
      >
        基本信息
      </div>
      <!-- 基本信息输入框容器 -->
      <div>
        <!-- 商品类型下拉选择框 -->
        <div class="flex_y_center margin_top_20">
          <div style="width: 80px; text-align: right">
            <span>*</span>
            商品分组：
          </div>
          <el-select
            v-model="formLabelAlign.method_id"
            clearable
            :disabled="goodsId != 0"
            placeholder="请选择分组"
          >
            <el-option
              v-for="(item, index) of typeOptions"
              :key="index"
              :label="item.method_name"
              :value="item.id"
            />
          </el-select>
          <el-link
            v-if="goodsId == 0"
            style="margin: 0 5px"
            type="primary"
            @click="openDislog('新增分组')"
          >
            新增
          </el-link>
          <el-link
            v-if="goodsId == 0"
            type="primary"
            @click="refresh('商品类型')"
          >
            刷新
          </el-link>
        </div>
        <!-- 商品类别 -->
        <div class="flex_y_center margin_top_20">
          <div style="width: 80px; text-align: right">
            <span>*</span>
            商品类别：
          </div>
          <el-select
            v-model="formLabelAlign.method_type_id"
            clearable
            :disabled="!formLabelAlign.method_id"
            placeholder="请选择类别"
          >
            <el-option
              v-for="(item, index) of methodList"
              :key="index"
              :label="item.type_name"
              :value="item.id"
            />
          </el-select>
          <el-link
            :disabled="!formLabelAlign.method_id"
            style="margin: 0 5px"
            type="primary"
            @click="openDislog('新增类别')"
          >
            新增
          </el-link>
          <el-link
            :disabled="!formLabelAlign.method_id"
            type="primary"
            @click="refresh('类别')"
          >
            刷新
          </el-link>
        </div>
        <!-- 商品供应商下拉选择框 -->
        <div
          v-if="goodsTypeName == '实物商品' || goodsTypeName == '电子卡券'"
          class="flex_y_center margin_top_20"
        >
          <div style="width: 80px; text-align: right">
            <span>*</span>
            供应商：
          </div>
          <el-select
            v-model="formLabelAlign.supplier_id"
            clearable
            :disabled="goodsId != 0"
            :filter-method="searchSupplier"
            filterable
            placeholder="请选择供应商"
          >
            <el-option
              v-for="(item, index) of supplierOptions"
              :key="index"
              :label="item.supplier_name"
              :value="item.id"
            />
          </el-select>
          <el-link
            v-if="goodsId == 0"
            style="margin: 0 5px"
            type="primary"
            @click="openDislog('新增供应商')"
          >
            新增
          </el-link>
          <el-link
            v-if="goodsId == 0"
            type="primary"
            @click="refresh('供应商')"
          >
            刷新
          </el-link>
        </div>
        <!-- 商品名输入 -->
        <label class="flex_y_center margin_top_20">
          <div style="width: 80px; text-align: right">
            <span>*</span>
            {{ goodsName }}：
          </div>
          <div style="width: 30%">
            <el-input
              v-model="formLabelAlign.goods_name"
              :placeholder="'请输入' + goodsName"
            />
          </div>
        </label>
        <!-- 副标题输入 -->
        <label class="flex_y_center margin_top_20">
          <div style="width: 80px; text-align: right">副标题：</div>
          <div style="width: 30%">
            <el-input
              v-model="formLabelAlign.goods_sub_name"
              placeholder="请输入副标题"
            />
          </div>
        </label>
        <!-- 单位输入 -->
        <label class="flex_y_center margin_top_20">
          <div style="width: 80px; text-align: right">
            <span>*</span>
            单位：
          </div>
          <div style="width: 15%">
            <el-input v-model="formLabelAlign.unit" placeholder="请输入单位" />
          </div>
        </label>
      </div>
    </div>
    <!-- 实物商品 -->
    <Real-goods
      v-if="formLabelAlign.type_id == 1"
      :o-goods-details-info="goodsDetailsInfo"
      @sendData="addGoods"
    />
    <!-- 虚拟商品 -->
    <Virtual-goods
      v-else-if="formLabelAlign.type_id == 2"
      :o-goods-details-info="goodsDetailsInfo"
      @sendData="addGoods"
    />
    <!-- 电子卡卷商品 -->
    <Cardroll-goods
      v-else-if="formLabelAlign.type_id == 3"
      :o-goods-details-info="goodsDetailsInfo"
      @sendData="addGoods"
    />
    <!-- 课程商品 -->
    <Course-goods
      v-else-if="formLabelAlign.type_id == 4"
      :o-goods-details-info="goodsDetailsInfo"
      @sendData="addGoods"
    />
    <!-- 定金服务商品 -->
    <Deposit-goods
      v-else-if="formLabelAlign.type_id == 5"
      :o-goods-details-info="goodsDetailsInfo"
      @sendData="addGoods"
    />
    <!-- 检验报告 -->
    <Inspection-goods
      v-else-if="formLabelAlign.type_id == 6"
      :o-goods-details-info="goodsDetailsInfo"
      @sendData="addGoods"
    />
    <!-- 辅助治疗 -->
    <AuxiliaryGoods
      v-else-if="formLabelAlign.type_id == 7"
      :o-goods-details-info="goodsDetailsInfo"
      @sendData="addGoods"
    />
    <!-- 药品 -->
    <DrugGoods
      v-else-if="formLabelAlign.type_id == 8"
      :o-goods-details-info="goodsDetailsInfo"
      @sendData="addGoods"
    />
    <!-- 处方 -->
    <PrescriptionGoods
      v-else-if="formLabelAlign.type_id == 9"
      :o-goods-details-info="goodsDetailsInfo"
      @sendData="addGoods"
    />

    <!-- 新增商品类型，供应商对话框 -->
    <el-dialog
      :title="dialogTitle"
      :visible.sync="dialogAddVisible"
      @closed="dialogTitle = ''"
    >
      <GoodsType
        v-if="dialogTitle == '新增分组'"
        @send="dialogAddVisible = false"
      />
      <Method
        v-else-if="dialogTitle == '新增类别'"
        :o-method-id="formLabelAlign.method_id"
        @send="dialogAddVisible = false"
      />
      <Supplier
        v-else-if="dialogTitle == '新增供应商'"
        @send="dialogAddVisible = false"
      />
    </el-dialog>
  </div>
</template>

<script>
  import {
    getRelatedProducts,
    getSupplierInfo,
    getCommodityType,
    addCommodity,
    goodsDetails,
  } from '@/api/commodity'
  import { getMethodType } from '@/api/commodityType'

  export default {
    components: {
      Supplier: () => import('./components/supplier.vue'),
      GoodsType: () => import('./components/goodstype.vue'),
      Method: () => import('./components/method.vue'),

      RealGoods: () => import('./components/realGoods.vue'),
      VirtualGoods: () => import('./components/virtualGoods.vue'),
      CardrollGoods: () => import('./components/cardrollGoods.vue'),
      CourseGoods: () => import('./components/courseGoods.vue'),
      DepositGoods: () => import('./components/depositGoods.vue'),
      InspectionGoods: () => import('./components/inspectionGoods.vue'),
      AuxiliaryGoods: () => import('./components/auxiliaryGoods.vue'),
      DrugGoods: () => import('./components/drugGoods.vue'),
      PrescriptionGoods: () => import('./components/prescriptionGoods.vue'),
    },
    props: {
      goodsId: {
        type: Number,
        default: 0,
      },
      goodsType: {
        type: String,
        default: '',
      },
      oTypeCode: {
        type: String,
        default: '',
      },
    },
    data() {
      return {
        lang: JSON.parse(window.localStorage.getItem('lang')),
        interLoad: true, // 控制页面加载样式

        relatedProducts: [], // 存放关联商品
        counter: 0,
        typeOptions: [], // 商品分组
        methodList: [], // 类别列表
        supplierOptions: [], // 存放供应商列表

        goodsDetailsInfo: {}, // 存放获取到的商品详情信息，传递给各个子组件

        formLabelAlign: {
          type_id: '', // 关联商品id
          method_id: '', // 商品分组id
          method_type_id: '', // 商品分组类型id
          supplier_id: '', // 供应商id
          goods_name: '', // 商品名称
          goods_sub_name: '', // 商品副标题
          unit: '', // 商品单位
        },

        dialogTitle: '', // 对话框标题
        dialogAddVisible: false, // 控制新增对话框显示隐藏
        goodsTypeName: '',
      }
    },
    computed: {
      goodsName() {
        let name = '商品名'
        if (this.goodsTypeName == '课程' || this.goodsTypeName == '定金服务')
          name = JSON.parse(window.localStorage.getItem('lang')).goods
            .service_name

        return name
      },
    },
    watch: {
      // 监听type_id变化，将id新值存入store中
      'formLabelAlign.type_id'(newValue) {
        // if (newValue == 6) this.$router.push('/report/report?type=report')
        if (newValue == 6)
          this.$router.push({
            name: 'ReportList',
            params: { type: 'report' },
          })
        this.$store.commit('goods/setGoodsTypeId', newValue)
        // 检索列表数组将当前选中的关联类型名称存入store
        for (let item of this.relatedProducts) {
          if (item.id == newValue) {
            this.$store.commit('goods/setGoodsTypeName', item.type_name)
          }
        }
      },
      'formLabelAlign.method_id'(newValue) {
        if (newValue) {
          this.getMethod()
          // 检索获取当前选择的分组名称
          for (let item of this.typeOptions) {
            if (item.id == newValue) {
              this.$store.commit('goods/setMethodName', item.method_name)
              break
            }
          }
        } else this.formLabelAlign.method_type_id = ''
      },
    },
    created() {
      this.getAssociation()
      this.getSupplier()
    },
    methods: {
      // 获取商品类型
      getType() {
        const data = {
          type_id: this.formLabelAlign.type_id,
          type_code: this.oTypeCode || '',
        }
        getCommodityType(data).then((res) => {
          this.typeOptions = [] // 循环赋值前将承载其数据的数组清空
          this.interLoad = false // 关闭加载动画
          if (res.data) {
            if (this.oTypeCode) {
              this.typeOptions.push(res.data)
              this.formLabelAlign.method_id = res.data.id
            } else this.typeOptions = res.data
          }
        })
      },
      // 获取供应商
      getSupplier(searchVal) {
        this.supplierOptions = []
        const params = {
          supplier_name: searchVal,
        }
        getSupplierInfo(params).then((res) => {
          this.supplierOptions = res.data
        })
      },
      // 关键字模糊供应商信息
      searchSupplier(val) {
        this.getSupplier(val)
      },
      // 获取关联商品列表
      getAssociation() {
        getRelatedProducts().then((res) => {
          this.relatedProducts = res.data // 将关联商品列表存放在 commodityType 变量中

          if (this.goodsId) {
            this.getGoodsDetails()
          } else if (this.goodsType) {
            const typeArr = []
            for (let item of this.relatedProducts) {
              if (item.type_code == this.goodsType) {
                typeArr.push(item)
                this.formLabelAlign.type_id = item.id
              }
            }
            this.relatedProducts = typeArr
            this.getType()
          } else {
            this.formLabelAlign.type_id = this.relatedProducts[0].id // 初始化当前关联商品id
            this.goodsTypeName = '实物商品'
            this.getType()
          }
        })
      },
      // 获取商品详情
      getGoodsDetails() {
        if (this.goodsId) {
          const params = {
            goods_id: this.goodsId,
          }
          goodsDetails(params).then((res) => {
            this.goodsDetailsInfo = res.data
            // 循环遍历将相同数据拿出
            for (let item in this.formLabelAlign) {
              this.formLabelAlign[item] = res.data[item]
            }
            this.getType() // 获取商品类型
            // 将当前商品对应id的关联类型取出
            let typeArr = []
            for (let item of this.relatedProducts) {
              if (this.formLabelAlign.type_id == item.id) {
                typeArr.push(item)
                this.formLabelAlign.type_id = item.id
                break
              }
            }
            this.relatedProducts = typeArr // 将关联商品列表存放在 commodityType 变量中
          })
        }
      },
      // 获取商品分组类别
      getMethod() {
        const data = {
          method_id: this.formLabelAlign.method_id,
        }
        getMethodType(data).then((res) => {
          this.methodList = res.data
          if (this.methodList.length == 0)
            this.formLabelAlign.method_type_id = ''
        })
      },
      // 选择关联商品
      chooseAssoc(item, index) {
        // 循环初始化数据
        for (let item in this.formLabelAlign) {
          if (item != 'goods_id') {
            this.formLabelAlign[item] = ''
          }
        }
        this.typeOptions = []
        this.methodList = []
        this.formLabelAlign.type_id = item.id
        this.counter = index
        this.goodsTypeName = item.type_name
        this.goodsTypeName == '课程'
          ? (this.formLabelAlign.unit = '节')
          : (this.formLabelAlign.unit = '')
        this.goodsTypeName != '实物商品' && this.goodsTypeName != '电子卡券'
          ? (this.formLabelAlign.supplier_id =
              window.localStorage.getItem('mec_id'))
          : (this.formLabelAlign.supplier_id = '')

        this.getType()
      },
      // 打开新增对话框
      openDislog(title) {
        this.dialogTitle = title
        this.dialogAddVisible = true
      },
      // 根据name参数的值不同调用不同参数
      refresh(name) {
        if (name == '商品类型') this.getType()
        else if (name == '类别') this.getMethod()
        else this.getSupplier()
      },
      // 添加商品
      addGoods(formData) {
        let submintBool = true
        // 检索基本数据除是否有未填写的字段
        for (let item in this.formLabelAlign) {
          if (
            item != 'goods_id' &&
            item != 'type_id' &&
            item != 'goods_sub_name' &&
            item != 'goods_content'
          ) {
            if (
              this.goodsTypeName != '实物商品' &&
              this.goodsTypeName != '电子卡券'
            ) {
              if (item != 'supplier_id') {
                if (this.formLabelAlign[item] == '') {
                  this.$message.error('基本信息处有未填写')
                  submintBool = false
                  break
                }
              }
            } else {
              if (this.formLabelAlign[item] == '') {
                this.$message.error('基本信息处有未填写')
                submintBool = false
                break
              }
            }
          }
        }

        if (submintBool) {
          const params = { ...this.formLabelAlign, ...formData }
          params.id = this.goodsId || ''
          // 如果为多规格的话那么，把 goods_spec 变成json
          if (params.is_many_attribute == 'Y') {
            // params.goods_price = ''
            // 防止用户重复点击后，params.goods_spec进行多次转字符串操作
            if (typeof params.goods_spec != 'string') {
              params.goods_spec = JSON.stringify(params.goods_spec)
            }
          }
          if (params.is_remind == 'Y') {
            if (typeof params.goods_remind != 'string') {
              params.goods_remind = JSON.stringify(params.goods_remind)
            }
            if (typeof params.remind_fields != 'string') {
              params.remind_fields = JSON.stringify(params.remind_fields)
            }
          } else {
            params.remind_fields = ''
          }
          if (params.goods_package) {
            if (typeof params.goods_package != 'string')
              params.goods_package = JSON.stringify(params.goods_package)
          }
          if (params.extend_fields) {
            if (typeof params.extend_fields != 'string') {
              params.extend_fields = JSON.stringify(params.extend_fields)
            }
          }
          addCommodity(params).then(() => {
            const hintTxt = this.formLabelAlign.id ? '编辑' : '添加'
            this.$message.success(
              this.formLabelAlign.goods_name + hintTxt + '成功'
            )
            this.$emit('send')
          })
        }
      },
    },
  }
</script>

<style scoped>
  .padding_15 {
    padding: 15px;
  }
  .background_gray {
    background-color: rgb(248, 248, 248);
  }

  .margin_top_20 {
    margin-top: 20px;
  }
  span {
    color: red;
  }

  .goods_type_items {
    padding: 15px 30px;
    display: inline-block;
    margin: 15px 15px 15px 0;
    border: 1px solid rgba(226, 226, 226, 0.5);
    border-radius: 5px;
    text-align: center;
    cursor: pointer;
    transition: 0.5s;
  }
  .goods_type_items:hover {
    border: 1px solid dodgerblue;
  }
  .select_style {
    background-color: rgba(226, 226, 226, 0.5);
    color: rgb(24, 144, 255);
  }
</style>
